<?php

namespace App\Http\Controllers\user;

use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\others\UploadFileController;
use App\models\forum\Replie;
use App\models\forum\Topic;
use App\models\Notification;
use App\models\user\EmailToken;
use App\models\user\User;
use App\other\TokenType;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str as Strin;
use Validator;

class UserInfoController extends Controller{

    public function __construct(){
    }

    public function userActive(Request $request){
        $validator = Validator::make($request->all(),[
            'id'    => 'required|integer|exists:email_tokens,id',
            'token' => 'required|min:32|max:32|exists:email_tokens,token'
        ]);

        if ($validator->fails()){
            return redirect('/login')->with(['_error' => '邮箱验证失败']);
        }

        $token = EmailToken::where('id', $request->get('id'))
            ->where('token', $request->get('token'))
            ->where('dead_time', '>=', time())->first();
        if (empty($token) || $token->type != TokenType::TOKEN_REGISTER_TYPE){
            return redirect('/login')->with(['_error' => '无法验证邮箱']);
        }

        $user = User::find($token->uid);
        if (empty($user)){
            return redirect('/login')->with(['_error' => '验证用户失败']);
        }
        $user->verified = 1;
        $user->save();
        EmailToken::destroy($token->id);
        return redirect('/login')->with(['status' => '验证成功']);
    }
    public function info($uid, Request $request){
        $user = User::findOrFail($uid);
        if (empty($user)){
            return view('errors.404');
        }
        $topics = Topic::where('uid', $user->id)
            ->orderby('created_at', 'DESC')
            ->paginate(10);
        $replies = Replie::where('uid', $user->id)
            ->orderby('created_at', 'DESC')
            ->paginate(10);
        return view('user.info', compact('user', 'topics', 'replies'));
    }
    public function edit(){
        $user = User::find(Auth::user()->id);
        if (empty($user)){
            return view('errors.404');
        }
        return view('user.edit', compact('user'));
    }
    public function update(Request $request){
        $v = Validator::make($request->all(), [
            'name'          => 'required|max:16',
            'email'         => 'required|email|max:64',
            'truename'      => 'max:32',
            'city'          => 'max:32',
            'company'       => 'max:32',
            'weiboname'     => 'max:32',
            'weibourl'      => 'url|max:255',
            'weblink'       => 'url|max:255',
            'wechatqrcode'  => 'file',
            'paymentqrcode' => 'file',
            'introduction'  => 'max:255'
        ]);

        if ($v->fails()) {
            return redirect()
                ->back()
                ->withErrors($v->getMessageBag()->getMessages())
                ->withInput($request->all());
        }

        $input = $request->all();
        if ($input['name'] != Auth::user()->name){
            $tem = User::where('name', $input['name'])->get();
            if (count($tem)){
                if (!empty(User::where('email', $request->get('email'))->first())) {
                    return redirect()
                        ->back()
                        ->withErrors(['name' => '名称已存在'])
                        ->withInput($request->all());
                }
            }
        }
        unset($input['_token']);
        unset($input['_method']);
        $user = User::findOrFail(Auth::user()->id);
        if ($user->email != $request->get('email')) {
            if (!empty(User::where('email', $request->get('email'))->first())) {
                return redirect()
                    ->back()
                    ->withErrors(['email' => '邮箱已存在'])
                    ->withInput($request->all());
            }
            $user->email = $input['email'];
            $input['verified'] = 0;
            $input['remember_token'] = Strin::random(60);
            RegisterController::sendRegisterEmail($user);
            Auth::logout();
        }
        if ($request->file('wechatqrcode') != null) {
            $wechatqrcode = UploadFileController::getImgPateh($request, 'wechatqrcode');
            if ($wechatqrcode != -1) {
                $input['wechatqrcode'] = $wechatqrcode;
            }
        }
        if ($request->file('paymentqrcode') != null){
                $paymentqrcode = UploadFileController::getImgPateh($request, 'paymentqrcode');
            if ($paymentqrcode != -1) {
                $input['paymentqrcode'] = $paymentqrcode;
            }
        }
        User::where('id', $user->id)->update($input);
        return redirect()->back()->with(['status' => '更新成功']);
    }
    public function avatar(){
        return view('user.avatar');
    }
    public function updateAvatar(Request $request){
        $v = Validator::make($request->all(), [
            'profile' => 'required|file',
        ]);

        if ($v->fails()) {
            return redirect()
                ->back()
                ->withErrors($v->getMessageBag()->getMessages())
                ->withInput($request->all());
        }

        $profile = UploadFileController::getImgPateh($request, 'profile');
        if ($profile != -1) {
            $user = Auth::user();
            $user->profile = $profile;
            $user->save();
        }
        return redirect()->back();
    }
    public function binding(){
        return view('user.binding');
    }
    public function notify(){
        return view('user.notify');
    }
    public function updateNotify(Request $request){
        $notify = $request->get('notify');
        $user   = Auth::user();
        if (is_null($notify)){
            $user->notify = 0;
        }else{
            $user->notify = 1;
        }
        $user->save();
        return redirect()->back();
    }
    public function notifications(){
        $notifications = Notification::where('uid', Auth::id())->orderby('updated_at', 'desc')->get();
        User::where('id', Auth::id())->update(['notification_count' => 0]);
        return view('user.notification', compact('notifications'));
    }
}
